package com.wqr.it.ecwdr.service;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.wqr.it.ecwdr.dao.IOptionsDao;
import com.wqr.it.ecwdr.entity.Token;
import com.wqr.it.ecwdr.repository.TokenRepository;
import com.wqr.it.ecwdr.util.DateUtils;
import com.wqr.it.ecwdr.vo.OptionsVO;

@Service
public class OptionService {
	private static final Logger log = LoggerFactory.getLogger("INFO");
	private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
	@Autowired  
    private IOptionsDao optionsDao;
	@Autowired
	private TokenRepository tokenRepository;

	public int generateToken(String key, boolean refresh) {
		if (StringUtils.isEmpty(key)) {
			return -2;
		}
		int token = Integer.parseInt(sdf.format(new Date()));
		if (refresh) {
			Token tokenEntity = new Token();
			tokenEntity.setName(key);
			tokenEntity.setValue(token);
			tokenRepository.save(tokenEntity);
		}
		
		OptionsVO optionsVO = optionsDao.getOptions(key);
		
		//log.info(optionsVO);
		if (optionsVO != null) {
			if (refresh) {
				optionsVO.setValue(token + "");
				optionsVO.setAttr1("N");
				optionsVO.setAttr2(DateUtils.currentDate());
				
				optionsDao.updateOptions(optionsVO);
				optionsVO = optionsDao.getOptions(key);
			}
			try {
				token = Integer.parseInt(optionsVO.getValue());
			} catch(NumberFormatException e) {
				token = -1;
				log.error("Fail to get saller token: " + optionsVO);
			}
		}
		return token;
	}
	

}
